package com.langsin.Search;
/**
@Auther: MFM
@Date: 2021/8/18 - 08 - 18 - 16:13 
@version: 1.0
*/

public class BinarySearch {

    public static int binarySearch(int[] arr,int left,int right,int value){
        //递归终止条件
        if (left>right){
            return -1;
        }

        if (value<arr[0]||value>arr[arr.length-1]){
            return -1;
        }

        int mid = (left+right)/2;

        int midValue = arr[mid];

        if (value>midValue){
            //向右递归
            return binarySearch(arr,mid+1,right,value);
        }else if (value<midValue){
            //向左递归
            return binarySearch(arr,left,mid-1,value);
        }else {
            //找到数据，终止递归
            return mid;
        }
    }

    public static void main(String[] args) {
        int[] arr = {3, 11, 13, 92, 1314, 1234};
        int index = binarySearch(arr,0,arr.length-1,3);
        if (index == -1){
            System.out.println("数列中无此元素");
        }else {
            System.out.println("元素下标："+index);
        }
    }
}
